package com.slipper.system.icon.service;

import com.google.gson.reflect.TypeToken;
import com.slipper.core.cache.CacheKey;
import com.slipper.core.cache.CacheUtil;
import com.slipper.system.icon.bo.IconBO;
import com.slipper.system.icon.dao.IconDao;
import com.slipper.core.transaction.ReadTransactional;
import com.slipper.core.transaction.WriteTransactional;
import com.slipper.util.Tool;
import com.slipper.util.UUID;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;

import java.util.List;

@Service
@ReadTransactional
public class IconService {
    @Resource
    private IconDao iconDao;

    public IconBO queryBy(String id) {
        return iconDao.queryBy(id);
    }

    @WriteTransactional
    public IconBO save(IconBO bo) {
        if (Tool.isBlank(bo.getBuiltin())) {
            bo.setBuiltin("0");
        }
        bo.setId(UUID.getUUID());
        bo.setCreateTime(System.currentTimeMillis());
        this.iconDao.insert(bo);
        CacheUtil.remove(CacheKey.Icon.KEY);
        return bo;
    }

    @WriteTransactional
    public void saveList(List<IconBO> iconList) {
        if (iconList == null) return;

        iconList.forEach(icon -> {
            if (iconDao.queryBy(icon.getId()) != null) {
                iconDao.update(icon);
            } else {
                icon.setCreateTime(System.currentTimeMillis());
                iconDao.insert(icon);
            }
        });

        CacheUtil.remove(CacheKey.Icon.KEY);
    }

    @WriteTransactional
    public Integer delete(String id) {
        CacheUtil.remove(CacheKey.Icon.KEY);
        return iconDao.delete(id);
    }

    public List<IconBO> queryList(IconBO bo) {
        return this.iconDao.queryList(bo);
    }

    public List<IconBO> queryAll() {
        List<IconBO> iconList = CacheUtil.get(CacheKey.Icon.KEY, new TypeToken<List<IconBO>>(){}.getType());
        if (iconList == null) {
            iconList = this.iconDao.queryList(new IconBO());
            CacheUtil.set(CacheKey.Icon.KEY, iconList, 60 * 60);
        }
        return iconList;
    }
}
